﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Admin.NET.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Web;

namespace Admin.NET.Application
{
    /// <summary>
    /// 设备报警服务
    /// </summary>
    [ApiDescriptionSettings("仓库作业", Name = "LesDeviceWaring", Order = 100)]
    [Route("api/[Controller]")]
    public class LesDeviceWaringService : ILesDeviceWaringService, IDynamicApiController, ITransient
    {
        private readonly IRepository<LesDeviceWaring,MasterDbContextLocator> _lesDeviceWaringRep;
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();

        /// <summary>
        /// 
        /// </summary>
        public LesDeviceWaringService(
            IRepository<LesDeviceWaring,MasterDbContextLocator> lesDeviceWaringRep
            ,IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep
            ,IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep
            ,ISysExcelTemplateService sysExcelTemplateService
        )
        {
            _lesDeviceWaringRep = lesDeviceWaringRep;
         _sysDictTypeRep = sysDictTypeRep;
         _sysDictDataRep = sysDictDataRep;
         _sysExcelTemplateService = sysExcelTemplateService;
        }

        /// <summary>
        /// 分页查询设备报警
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<LesDeviceWaringOutput>> Page([FromQuery] LesDeviceWaringSearch input)
        {
            var lesDeviceWarings = await _lesDeviceWaringRep.DetachedEntities
                                     .Where(!string.IsNullOrEmpty(input.DeviceName), u => EF.Functions.Like(u.DeviceName, $"%{input.DeviceName.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.FaultName), u => EF.Functions.Like(u.FaultName, $"%{input.FaultName.Trim()}%"))
                                     .Where(input.StartTime != null, u => u.StartTime == input.StartTime)
                                     .Where(input.EndTime != null, u => u.EndTime == input.EndTime)
                                     .OrderBy(PageInputOrder.OrderBuilder<LesDeviceWaringSearch>(input))
                                     .ProjectToType<LesDeviceWaringOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return lesDeviceWarings;
        }

        /// <summary>
        /// 不分页查询设备报警列表
        /// </summary>
        /// <param name="input">设备报警查询参数</param>
        /// <returns>(设备报警)实例列表</returns>
        [HttpGet("listNonPage")]
        public async Task<List<LesDeviceWaringOutput>> ListNonPageAsync([FromQuery] LesDeviceWaringSearchNonPage input)
        {
            var pDeviceName = input.DeviceName?.Trim() ?? "";
            var pFaultName = input.FaultName?.Trim() ?? "";
            var pStartTime = input.StartTime;
            var pEndTime = input.EndTime;
            var lesDeviceWarings = await _lesDeviceWaringRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(pDeviceName), u => EF.Functions.Like(u.DeviceName, $"%{pDeviceName}%")) 
                .Where(!string.IsNullOrEmpty(pFaultName), u => EF.Functions.Like(u.FaultName, $"%{pFaultName}%")) 
                .Where(pStartTime != null, u => u.StartTime == pStartTime)
                .Where(pEndTime != null, u => u.EndTime == pEndTime)
            .OrderBy(PageInputOrder.OrderNonPageBuilder(input))
            .ProjectToType<LesDeviceWaringOutput>()
            .ToListAsync();
            return lesDeviceWarings;
        }


        /// <summary>
        /// 增加设备报警
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add(AddLesDeviceWaringInput input)
        {
            var lesDeviceWaring = input.Adapt<LesDeviceWaring>();
            await _lesDeviceWaringRep.InsertAsync(lesDeviceWaring);
        }

        /// <summary>
        /// 删除设备报警
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteLesDeviceWaringInput input)
        {
            var lesDeviceWaring = await _lesDeviceWaringRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _lesDeviceWaringRep.DeleteAsync(lesDeviceWaring);
        }

        /// <summary>
        /// 更新设备报警
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateLesDeviceWaringInput input)
        {
            var isExist = await _lesDeviceWaringRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var lesDeviceWaring = input.Adapt<LesDeviceWaring>();
            await _lesDeviceWaringRep.UpdateAsync(lesDeviceWaring,ignoreNullValues:true);
        }

        /// <summary>
        /// 获取设备报警
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<LesDeviceWaringOutput> Get([FromQuery] QueryeLesDeviceWaringInput input)
        {
            return (await _lesDeviceWaringRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<LesDeviceWaringOutput>();
        }

        /// <summary>
        /// 获取设备报警列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<LesDeviceWaringOutput>> List([FromQuery] LesDeviceWaringInput input)
        {
            return await _lesDeviceWaringRep.DetachedEntities.ProjectToType<LesDeviceWaringOutput>().ToListAsync();
        }    
         /// <summary>
        /// Excel模板导入设备报警功能
        /// </summary>
        /// <param name="file">Excel模板文件</param>
        /// <param name="importExcelType">Excel导入方式</param>
        /// <returns>导入的记录数</returns>
        [HttpPost("fromExcel")]
        public async Task<int> FromExcelAsync(IFormFile file, [FromQuery] ImportExcelType importExcelType)
        {
            int size = 200;
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("LesDeviceWaring", "v2");
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var keys = excelTemplate.UnionUniqueFields.Split(",") ?? Array.Empty<string>();
            for (var i = 0; i < keys.Length; i++) 
            {
                keys[i] = keys[i]?.Trim() ?? string.Empty;
            }
            ExcelUtil.FromExcel(file, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, out List<string> headers, out List<List<object?>> data, out string sheetName);
            List<LesDeviceWaringOutput> lesDeviceWaringList = DataConvertUtil.ToObjectList(headers, data, sheetName, keys, excelTemplate?.DataStartLine ?? 2, out Dictionary<string, LesDeviceWaringOutput> dict);
            List<Dictionary<string, object>> uniqueKeyValueDictList = lesDeviceWaringList.ParseUniqueKeyValueDictList(keys.ToList(), excelTemplate?.DataStartLine ?? 2, sheetName);
            var filters = DataConvertUtil.GetExpressionListByUniqueDict<LesDeviceWaring>(keys.ToList(), uniqueKeyValueDictList, size);
            var selectKeys = keys.ToList();
            if(!selectKeys.Contains("Id")) selectKeys.Add("Id");
            var selector = DataConvertUtil.GetSelectExpressionListByUniqueDict<LesDeviceWaring, LesDeviceWaringOutput>(selectKeys);
            List<LesDeviceWaring> updates = new();
            List<LesDeviceWaring> adds = new();

            lock (_lock)
            {
                foreach (var filter in filters)
                {
                    var lesDeviceWaringExistSubList = _lesDeviceWaringRep.Where(filter).Select(selector).ToList();
                    lesDeviceWaringExistSubList.ForEach(x => 
                    {
                        var k = DataConvertUtil.GetKey(x, keys);
                        if (dict.ContainsKey(k)) dict[k].Id = x.Id;
                    });
                }
                foreach (var lesDeviceWaring in lesDeviceWaringList) 
                {
                    if (lesDeviceWaring.Id > 0)
                    {
                        if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.Add(lesDeviceWaring.Adapt<LesDeviceWaring>());
                    }
                    else 
                    {
                        adds.Add(lesDeviceWaring.Adapt<LesDeviceWaring>());
                    }
                }

                if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.ForEach(x => _lesDeviceWaringRep.Update(x));
                

                var maxId = _lesDeviceWaringRep.DetachedEntities.OrderByDescending(x => x.Id).Select(x => x.Id).FirstOrDefault();
                adds.ForEach(x => x.Id = ++maxId);    
                Db.GetDbContext().Set<LesDeviceWaring>().AddRange(adds);  
                Db.GetDbContext().SaveChanges();
               
            }
            await Task.CompletedTask;
            return adds.Count;
        }

        /// <summary>
        /// 根据版本下载设备报警的Excel导入模板
        /// </summary>
        /// <param name="version">模板版本</param>
        /// <returns>下载的模板文件</returns>
        [HttpGet("downloadExcelTemplate")]
        public async Task<IActionResult> DownloadExcelTemplate([FromQuery] string version)
        {
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("LesDeviceWaring", version);
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var path = Path.Combine(@"\", excelTemplate.TemplateFileName);
            Stream ms = FileUtil.Download(path, excelTemplate.TemplateFileName);
            var fileName = HttpUtility.UrlEncode($"{excelTemplate.Name}导入模板.xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
        /// <summary>
        /// 根据设备报警查询参数导出Excel
        /// </summary>
        /// <param name="input">设备报警查询参数</param>
        /// <returns>导出的Excel文件</returns>
        [HttpGet("toExcel")]
        public async Task<IActionResult> ToExcelAsync([FromQuery] LesDeviceWaringSearchNonPage input)
        {
            var lesDeviceWaringList = await ListNonPageAsync(input);
            MemoryStream ms = new();
            DataConvertUtil.ToExcelData(lesDeviceWaringList, _sysDictTypeRep, _sysDictDataRep, out List<string> headers, 
                out List<List<object>> data, out string sheetName);
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("LesDeviceWaring", "v1");
            if (excelTemplate != null)
            {
                ExcelUtil.ToExcel(excelTemplate.TemplateFileName, headers, data, sheetName, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, ms);
            }
            else 
            {
                ExcelUtil.ToExcel(headers, data, sheetName, ms);
            }
            ms.Position = 0;
            var fileName = HttpUtility.UrlEncode($"{sheetName}[{DateTimeOffset.Now:yyyy-MM-dd}].xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
    }
}
